<?php
declare(strict_types=1);

namespace App\Controller\Admin\V1\PointPosition;

use App\Controller\Admin\AdminController;
use App\Helper\Utils;
use App\Job\PositionExportJob;
use App\Model\ExportFile;
use App\Model\PositionHasAdmin;
use App\Model\PositionUnit;
use App\Repositories\PointPositionRepository;
use App\Repositories\PositionHasAdminRepository;
use App\Repositories\PositionUnitRepository;
use App\Repositories\UserHasPositionRepository;
use App\Request\storePointPositionRequest;
use App\Services\QueueService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class PositionController extends AdminController
{
    /**
     * @Inject
     * @var QueueService
     */

    public $queue_service;

    public function list(){
        $admin = $this->request->getAttribute('admin');
        $rows = $this->request->input('rows',10);
        $search=[];
        $join=[];
        $district_id = $this->request->input('district_id','all');
        $category_id = $this->request->input('category_id','all');
        $name = $this->request->input('name','');
        $search=[];
        if($district_id!='all'){
            $search['district_id']=[
                'field' => 'district_id',
                'value' => $district_id
            ];
        }
        if($category_id!='all'){
            $search['category_id']=[
                'field' => 'category_id',
                'value' => $category_id
            ];
        }
        if($name!=''){
            $search['name']=[
                'field' => 'name',
                'value' => $name,
                'method' => 'like'
            ];
        }
//        if($admin->id!=1){
//            $join = [
//                'position_has_admin' => [
//                    'on' => ['point_position.id','=','position_has_admin.position_id'],
//                    'where'=>[[
//                        'field' => 'position_has_admin.admin_id',
//                        'value' => $admin->id,
//                    ]]
//                ]
//            ];
//        }

        $orderBy= [
            [
                'field' => 'id',
                'sort' => 'desc'
            ]
        ];

        $columns=[
            'point_position.*'
        ];

        $datas = PointPositionRepository::getInstance()->getList($columns,$search,['limit'=>$rows],$orderBy,$join,['category','district','mainunit']);

        return $this->response->success($datas);
    }

    public function detail(){
        $id = $this->request->input('id');
        $position = PointPositionRepository::getInstance()->getById($id);
        $position['partner_ids'] = PositionUnit::query()->where('position_id',$id)
            ->where('type',PositionUnit::TYPE_PARTER)->get()
            ->pluck('unit_id')->toArray();
        return $this->response->success($position);
    }

    public function store(storePointPositionRequest $request){
        $params = $request->all();
        $admin = $this->request->getAttribute('admin');
        $params['admin_id'] = $admin->id;
        DB::beginTransaction();
        try{
            $result = PointPositionRepository::getInstance()->store($params);
            if(!$result['success']){
                throw new \Exception('点位信息保存失败');
            }
            $position = $result['data'];
            $main_unit = PositionUnitRepository::getInstance()->one('*',[[
                'field' => 'position_id',
                'value' => $position->id
            ],[
                'field'=>'type',
                'value' => PositionUnit::TYPE_MAIN
            ]]);
            $is_insert_main=false;
            if(isset($params['main_unit_id'])){
                if(!$main_unit||$main_unit->unit_id!=$params['main_unit_id']){
                    $is_insert_main=true;
                }
                if($is_insert_main){
                    $main_unit_model = new PositionUnit();
                    $main_unit_model->position_id = $position->id;
                    $main_unit_model->type = PositionUnit::TYPE_MAIN;
                    $main_unit_model->unit_id = $params['main_unit_id'];
                    if(!$main_unit_model->save()){
                        throw new \Exception('责任单位保存失败');
                    }
                    if($main_unit){
                        PositionUnitRepository::getInstance()->delete($main_unit->id);
                    }
                }
            }
            if(isset($params['parter_unit_id'])){
                $partner_unit_ids = $params['parter_unit_id'];
                $select_tags = PositionUnit::where('position_id',$position->id)
                    ->where('type',PositionUnit::TYPE_PARTER)
                    ->get()
                    ->pluck('unit_id')
                    ->toArray();
                $delete_tags = array_merge(array_diff($select_tags,$partner_unit_ids));
                $add_tags = array_merge(array_diff($partner_unit_ids,$select_tags));
                if(!empty($delete_tags)){
                    PositionUnit::where('position_id',$position->id)
                        ->whereIn('unit_id',$delete_tags)
                        ->delete();
                }
                if(!empty($add_tags)){
                    foreach ($add_tags as $tag){
                        if($tag=='') continue;
                        $_tag = new PositionUnit();
                        $_tag->position_id = $position->id;
                        $_tag->unit_id = $tag;
                        $_tag->type = PositionUnit::TYPE_PARTER;
                        if(!$_tag->save()){
                            throw new \Exception('协作单位保存失败');
                        }
                    }
                }
            }
            DB::commit();
        }catch (\Throwable $e){
            DB::rollBack();
            return $this->response->error(10040,$e->getMessage());
        }

        return $this->response->success([
            'id' => $position->id
        ]);
    }

    public function delete(){
        $id = $this->request->input('id');
        $result =PointPositionRepository::getInstance()->delete($id);
        if($result){
            return $this->response->success($result['data']);
        }
        return $this->response->error(10000,$result['msg']);
    }

    public function listAssign(){
        $user_id = $this->request->input('user_id',0);
        $user_has_position_result = UserHasPositionRepository::getInstance()->all(['position_id'],[[
            'field' => 'user_id',
            'value' => $user_id
        ]]);
        $user_has_position_ids = collect($user_has_position_result)->pluck('position_id')->toArray();
        $rows = $this->request->input('rows',10);
        $search=[];
        $district_id = $this->request->input('district_id','all');
        $category_id = $this->request->input('category_id','all');
        $name = $this->request->input('name','');
        $search=[];
        if($district_id!='all'){
            $search['district_id']=[
                'field' => 'district_id',
                'value' => $district_id
            ];
        }
        if($category_id!='all'){
            $search['category_id']=[
                'field' => 'category_id',
                'value' => $category_id
            ];
        }
        if(!empty($user_has_position_ids)){
            $search['id']=[
                'field' => 'id',
                'value' => $user_has_position_result,
                'method' => 'notin'
            ];
        }
        if($name!=''){
            $search['name']=[
                'field' => 'name',
                'value' => $name,
                'method' => 'like'
            ];
        }
        $orderBy= [
            [
                'field' => 'id',
                'sort' => 'desc'
            ]
        ];
        $datas = PointPositionRepository::getInstance()->getList('*',$search,['limit'=>$rows],$orderBy,'',['category','district']);

        return $this->response->success($datas);
    }

    public function assignManager(){
        $position_id = $this->request->input('id',0);
        $has_admin_id_result = PositionHasAdminRepository::getInstance()->all(['admin_id'],[[
            'field'=>'position_id',
            'value' => $position_id
        ]]);
        $has_admin_id_arr = $has_admin_id_result->pluck('admin_id')->toArray();
        return $this->response->success($has_admin_id_arr);
    }

    public function assignManagerStore(){
        $position_id = $this->request->input('id',0);
        $admin_ids = $this->request->input('admin_ids',"");
        $admin_ids = explode(',',$admin_ids);
        $select_tags = PositionHasAdmin::where('position_id',$position_id)
            ->get()
            ->pluck('admin_id')
            ->toArray();
        $delete_tags = array_merge(array_diff($select_tags,$admin_ids));
        $add_tags = array_merge(array_diff($admin_ids,$select_tags));
        //return $this->response->success(['add'=>$add_tags,'delete'=>$delete_tags]);
        if(!empty($delete_tags)){
            PositionHasAdmin::where('position_id',$position_id)
                ->whereIn('admin_id',$delete_tags)
                ->delete();
        }
        if(!empty($add_tags)){
            foreach ($add_tags as $tag){
                if($tag=='') continue;
                $_tag = new PositionHasAdmin();
                $_tag->position_id = $position_id;
                $_tag->admin_id = $tag;
                if(!$_tag->save()){
                   return $this->response->error(10014,'保存失败');
                }
            }
        }
        return $this->response->success($this->request->all());
    }

    public function export(){
        $admin = $this->request->getAttribute('admin');
        $params = $this->request->all();
        if($admin->district_id){
            $params['district_id'] = $admin->district_id;
        }
        $hash_id = $params['hash_id'];
        $exists = ExportFile::query()->where('hash_id',$hash_id)->first();
        if(!$exists){
            $newname = Utils::createFileName().'.csv';
            $dir = '/uploads/export/'.date('Ym').'/'.date('d').'/';
            $folder = BASE_PATH.'/public'.$dir;
            if (!is_dir($folder)) {
                mkdir($folder, 0777, true);
            }
            $model = new ExportFile();
            $model->hash_id=$hash_id;
            $model->file_url = $dir.$newname;
            $model->type = 'thread';
            $model->params = json_encode($params);
            if(!$model->save()){
                return $this->response->error(10050,'创建导出失败');
            }
            $params['file_url'] = $dir.$newname;
            cache()->set('export_'.$hash_id,0);
            $this->queue_service->push(new PositionExportJob($params));
            return $this->response->success([
                'hash_id' => $hash_id,
                'progress' => 0,
                'file_url' => config('common.image_prefix').$dir.$newname
            ]);
        }
        return $this->response->success([
            'hash_id' => $hash_id,
            'progress' => cache()->get('export_'.$hash_id),
            'file_url' => config('common.image_prefix').$exists->file_url
        ]);
    }
}